package com.dkha.server.controllers;

import com.dkha.common.exception.DkException;
import com.dkha.common.page.PageParam;
import com.dkha.common.result.CommonResult;
import com.dkha.common.util.ExcelUtils;
import com.dkha.common.util.UtilValidate;
import com.dkha.server.annotation.NoRepeatSubmitAnnotation;
import com.dkha.server.modules.entities.FaceCameraEntity;
import com.dkha.server.modules.entities.faceCamera.FaceCameraExcel;
import com.dkha.server.modules.entities.faceCamera.FaceCameraInfo;
import com.dkha.server.modules.entities.faceCamera.InsertFaceCamera;
import com.dkha.server.services.FaceCameraService;
import com.dkha.server.system.modules.sys.entity.SysRegionEntity;
import com.dkha.server.system.modules.sys.enums.RegionLevelEnum;
import com.dkha.server.system.modules.sys.enums.RegionTopEnum;
import com.dkha.server.system.modules.sys.service.SysRegionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.dkha.common.systemcode.SystemCode.EXCEL_ERROR_DATA;

@RestController
@RequestMapping(value = "/camera")
@Api(tags = "摄像头管理")
@Slf4j
public class CameraController extends CommonResult {

    @Resource
    private SysRegionService sysRegionService;

    @Resource
    private FaceCameraService faceCameraServiceImpl;

    @ApiOperation(value = "摄像头列表")
    @PostMapping(value = "/getList")
    @RequiresPermissions("camera:list")
    public CommonResult getList(@ApiParam(required = true, name = "pageParam", value = "{\n" +
            "  \"note\": {\n" +
            "    \"cameraName\": \"摄像头名称\",\n" +
            "   \"cameraRegion\":\"摄像头区域\",\n" +
            "   \"cameratLocationtypeId\":\"位置类型\",\n" +

            "\"status\":\"是否运行 Y启动 N未启动\"\n" +
            "  },\n" +
            "  \"pageNo\": 1,\n" +
            "  \"pageSize\": 10,\n" +
            "  \"sort\": {\n" +
            "    \n" +
            "  },\n" +
            "  \"sex\": \"desc\"\n" +
            "}") @RequestBody PageParam pageParam) {

        return successResult(faceCameraServiceImpl.getPage(pageParam));
    }

    @ApiOperation(value = "全部摄像头列表")
    @GetMapping(value = "/getAllList")
//    @RequiresPermissions("camera:list")
    public CommonResult getAllList(String cameraName) {
        return successResult(faceCameraServiceImpl.getAll(cameraName));
    }


    @ApiOperation(value = "查看摄像头信息")
    @GetMapping(value = "/findById/{idCamera}")
    @RequiresPermissions("camera:info")
    public CommonResult findById(@PathVariable("idCamera") long idCamera) {
        return successResult(faceCameraServiceImpl.findById(idCamera));
    }

    @PostMapping(value = "/insert")
    @ApiOperation(value = "新增摄像头")
    @RequiresPermissions("camera:save")
    @NoRepeatSubmitAnnotation(prefix = "camera/insert")
    public CommonResult insert(@RequestBody @Valid InsertFaceCamera insertFaceCamera) {
        try {
            System.out.println("进入添加摄像头方法");
//            for (InsertFaceCamera insertFaceCamera1:insertFaceCamera){
//                faceCameraServiceImpl.insertCamera(insertFaceCamera1);
//            }
            faceCameraServiceImpl.insertCamera(insertFaceCamera);
            System.out.println(insertFaceCamera);
        } catch (DkException e) {
            return failResult(e.getMessage());
        } catch (Exception e) {
            log.error("添加摄像头异常===>", e.getMessage());
            return failResult("操作失败");
        }
        return successResult("添加成功");
    }


//    @ApiOperation(value = "获取摄像头卡口树状图")
//    @GetMapping(value = "/getBayonet")
//    public CommonResult getBayonet() {
//        return successResult(faceCameraServiceImpl.getBayonet(RegionTopEnum.FATHER.value()));
//    }

    @ApiOperation(value = "获取摄像头卡口树状图")
    @GetMapping(value = "/getBayonet")
    public CommonResult getBayonet() {
        List<SysRegionEntity> regionByLevel = sysRegionService.getRegionByLevel(RegionLevelEnum.ONE.value());
        List<List<Map<String, Object>>> lists = new ArrayList<>();
        List<Map<String, Object>> results = new ArrayList<>();
        for (SysRegionEntity region:regionByLevel) {
            List<Map<String, Object>> bayonet = faceCameraServiceImpl.getBayonet(region.getPid());
            //System.out.println(bayonet);
            results.add(bayonet.get(0));
        }
        return successResult(results);
    }


//    @ApiOperation(value = "获取摄像头区域树状图")
//    @GetMapping(value = "/getRegion")
//    public CommonResult getRegion() {
//        return successResult(faceCameraServiceImpl.getRegion(RegionTopEnum.FATHER.value()));
//    }

    @ApiOperation(value = "获取摄像头区域树状图")
    @GetMapping(value = "/getRegion")
    public CommonResult getRegion() {
        List<SysRegionEntity> regionByLevel = sysRegionService.getRegionByLevel(RegionLevelEnum.ONE.value());
        List<Map<String, Object>> lists = new ArrayList<>();
        for (SysRegionEntity region:regionByLevel) {
            List<Map<String, Object>> mapList = faceCameraServiceImpl.getRegion(region.getPid());
            lists.add(mapList.get(0));
        }
        return successResult(lists);
    }

    @ApiOperation(value = "获取当前区域下的摄像头")
    @GetMapping(value = "/getRegion/{regionId}")
    public CommonResult getRegionCamera(@PathVariable("regionId") long regionId) {
        return successResult(faceCameraServiceImpl.getCameraByRegionId(regionId));
    }

    @ApiOperation(value = "获取当前区域下尚未布控的摄像头")
    @GetMapping(value = "/getRegion/unControl/{regionId}")
    public CommonResult getRegionUnControlCamera(@PathVariable("regionId") long regionId) {
        return successResult(faceCameraServiceImpl.getRegionUnControlCamera(regionId));
    }

    @ApiOperation(value = "获取当前区域下的所有摄像头")
    @GetMapping(value = "/getRegion/all/{regionId}")
    public CommonResult getAllRegionCamera(@PathVariable("regionId") long regionId) {
        return successResult(faceCameraServiceImpl.getAllCameraByRegionId(regionId));
    }

    @ApiOperation(value = "删除摄像头")
    @GetMapping(value = "/delete/{idCamera}")
    @RequiresPermissions("camera:del")
    public CommonResult delete(@PathVariable("idCamera") long idCamera) {
        return successResult(faceCameraServiceImpl.delete(idCamera));
    }

    @ApiOperation(value = "更改摄像头状态")
    @GetMapping(value = "/{idCamera}/{status}")
    public CommonResult status(@PathVariable("idCamera") long idCamera, @PathVariable("status") boolean status) {
        return successResult(faceCameraServiceImpl.status(idCamera, status));
    }

    @ApiOperation(value = "修改摄像头")
    @PostMapping(value = "/update")
    @RequiresPermissions("camera:update")
    public CommonResult update(@RequestBody @Valid FaceCameraInfo faceCameraInfo) {
        return successResult(faceCameraServiceImpl.update(faceCameraInfo));
    }


    @ApiOperation(value = "经纬度查询摄像头信息")
    @GetMapping(value = "/findByCoordinate")
    public CommonResult findByCoordinate(@ApiParam(name = "经度") @RequestParam(name = "cameraLatitude") String cameraLongitude,
                                         @RequestParam(name = "cameraLatitude") String cameraLatitude) {
        FaceCameraEntity faceCameraInfo = faceCameraServiceImpl.findByCoordinate(cameraLongitude, cameraLatitude);
        if (UtilValidate.isNotEmpty(faceCameraInfo)) {
            return successResult(faceCameraInfo);
        }
        return failResult("未能查询到该摄像头");
    }

    @GetMapping(value = "/downloadExcel")
    @ApiOperation(value = "下载模板")
    public void downloadIncomeExcel(HttpServletResponse servletResponse) throws Exception {
        ExcelUtils.downloadTemplate(servletResponse, "摄像头导入模板");
    }

    @PostMapping(value = "/import")
    @ApiOperation(value = "摄像头导入功能")
    public CommonResult importDailyTimeStatisticsExcel(@RequestParam(name = "processFile", required = true) MultipartFile multipartFile,
                                                       HttpServletResponse response
    ) {
        List<FaceCameraExcel> data = faceCameraServiceImpl.importExcel(multipartFile);
        if (UtilValidate.isEmpty(data)) {
            return successResult("上传成功");
        }
        return failResult(EXCEL_ERROR_DATA.code, "存在错误数据", data);
    }
//    private CheckTtl checkTtl;
//    @GetMapping(value = "/test")
//    @ApiOperation(value = "下载模板")
//    public void test()  {
//        Lock lock = new Lock(new ConsulClient(), "lock-key", checkTtl);
//        try {
//            if (lock.lock(true, 500L, null)) {
//                log.info("Thread {} start!", 1);
//                // 处理业务逻辑
//                log.info("Thread {} end!", 2);
//            }else {
//                log.info("Thread {} end!", 3);
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } finally {
//            lock.unlock();
//        }
//    }


}
